export default {
  name: 'Login',
  data () {
    return {
      info: {},
      loginRules: {
        username: [
          { required: true, message: '请填写用户名', trigger: 'change' },
          { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请填写密码', trigger: 'change' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 表单重置
    resetHandler () {
      this.$refs.login.resetFields()
    },
    // 表单提交事件
    submitHandler () {
      this.$refs.login.validate(async valid => {
        if (!valid) {
          this.$message({
            type: 'warning',
            message: '请按照规则完整填写表单',
            duration: 1500
          })
          return
        }

        const { data, meta } = await this.$post('login', this.info)
        if (meta.status === 400) {
          this.$message({
            type: 'error',
            message: '用户名或密码错误, 请重新登录',
            duration: 3000
          })
          return
        }
        window.sessionStorage.setItem('token', data.token)
        // 登陆成功添加小提示
        this.$message({
          type: 'success',
          message: '登陆成功, 即将登陆',
          duration: 1500
        })

        setTimeout(() => {
          this.$router.push('/home')
        }, 1500)
      })
    }
  }
}
